package com.yiguantong.police.nfc;

import android.content.Intent;
import android.nfc.FormatException;
import android.os.Bundle;
import android.util.Log;

import com.yiguantong.police.BaseActivity;
import com.yiguantong.police.R;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NfcActivity extends BaseActivity {

    private String billNo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfc);
        new NfcUtils(NfcActivity.this);
        billNo = getIntent().getStringExtra("billNo");
    }

    //在onResume中开启前台调度
    @Override
    protected void onResume() {
        super.onResume();
        //设定intentfilter和tech-list。如果两个都为null就代表优先接收任何形式的TAG action。也就是说系统会主动发TAG intent。
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
        }
    }

    //在onNewIntent中处理由NFC设备传递过来的intent
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("====", "--------------NFC-------------");
        processIntent(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NfcUtils.mNfcAdapter = null;
    }

    //  这块的processIntent() 就是处理卡中数据的方法
    public void processIntent(Intent intent) {
        try {
            if (billNo == null) {
                // NfcUtils中获取卡中数据的方法
                String result = NfcUtils.readNFCFromTag(intent);
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(result);
                intent.putExtra("sResult", m.replaceAll("").trim());
                setResult(RESULT_OK, intent);
                NfcActivity.this.finish();
            } else {
                // 往卡中写数据
                NfcUtils.writeNFCToTag(billNo, intent);
                intent.putExtra("sResult", "写入成功");
                setResult(RESULT_OK, intent);
                NfcActivity.this.finish();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
    }

}
